package com.testdocs.client.project.initialselect;

import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.testdocs.client.ClientFactory;
import com.testdocs.client.project.ProjectInfo;
import com.testdocs.client.project.ProjectService;
import com.testdocs.client.project.ProjectServiceAsync;
import com.testdocs.client.project.create.CreateProjectPlace;
import com.testdocs.client.project.dashboard.DashboardPlace;
import com.testdocs.client.project.i18n.ProjectConstants;

public class SelectProjectActivity extends AbstractActivity {
	private ClientFactory clientFactory;

	public SelectProjectActivity(ClientFactory clientFactory) {
		this.clientFactory = clientFactory;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus) {
		ProjectConstants projectConstants = (ProjectConstants) GWT.create(ProjectConstants.class);
		
		clientFactory.getWaitingPopupPanel()
				.show(projectConstants.loadingProjectInfoStatus());
		ProjectServiceAsync service = GWT.create(ProjectService.class);
		service.getDefaultProject(new AsyncCallback<ProjectInfo>() {

			@Override
			public void onFailure(Throwable caught) {
				clientFactory.getRpcErrorHandler().handle(caught);
				clientFactory.getWaitingPopupPanel().hide();
			}

			@Override
			public void onSuccess(ProjectInfo result) {
				if (result == null) {
					clientFactory.getPlaceController().goTo(
							new CreateProjectPlace());
				} else {
					clientFactory.getPlaceController().goTo(
							new DashboardPlace(result.getProjectId()));
				}
				clientFactory.getWaitingPopupPanel().hide();
			}

		});
	}

}
